<template>
  <!-- 编辑弹出框 id,typeId,goodsId,sort -->
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
    <el-form ref="dataForm" :model="dataForm" label-width="100px">
      <el-form-item label="ID">
        <el-input v-model="dataForm.id" :disabled="true"></el-input>
      </el-form-item>

      <el-form-item label="类别">
        <el-select v-model="dataForm.typeId" placeholder="选择类别">
          <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="商品id">
        <goods-select :id.sync="dataForm.goodsId"></goods-select>
      </el-form-item>

      <el-form-item label="序号">
        <el-input v-model="dataForm.sort" type="number"></el-input>
      </el-form-item>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="medium" @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" size="medium" @click="dataFormSubmit">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import GoodsSelect from "./GoodsSelect.vue"
import * as HomeAPI from '@/api/home.js';

export default {
  name: 'homeGoodsEdit',
  components: {
    GoodsSelect,
  },
  props: {
    typeId: {
      type: Number,
      default: 0
    },

  },
  data() {
    return {
      dataForm: {
        id: 0
      }, //表单
      dialogVisible: false, //编辑框
    };
  },
  props: {
    typeId: {
      type: Number,
      default: 2
    },
    typeList: Array //选项数据 [{id:2,name:"为你推荐"},{id:3,name:"新品上线"},{id:4,name:"热销商品"}]
  },
  computed: {
    //弹框标题
    dialogTitle() {
      return !this.dataForm.id ? '新增' : '编辑';
    }
  },
  methods: {
    init(id) {
      this.dataForm.id = id || 0;
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields();
        if (id) {
          //如果是编辑
          HomeAPI.getDetailById(id)
            .then(result => {
              this.dataForm = result.data; //看接口文档，知道data是对应的用户对象
            })
            .catch(error => {
            });
        } else {
          //如果是新增
          this.setDataFormToDefault();
        }
      });
    },

    //提交确认
    dataFormSubmit() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          HomeAPI.save(this.dataForm)
            .then(() => {
              this.$message.success(`保存成功`);
              this.dialogVisible = false;
              this.$emit('refreshDataList'); //重新刷新列表数据
            })
            .catch(error => {
            });
        }
      });
    },

    setDataFormToDefault() {
      //初始默认值
      let defaultForm = {};
      defaultForm.id = 0;
      defaultForm.typeId = this.typeId; //Props传递的参数
      defaultForm.goodsId = null;
      defaultForm.sort = 1;
      this.dataForm = Object.assign({}, defaultForm);
    }

  }
};
</script>

<style scoped>
</style>
